home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 11654 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  53 lines

  1. Path: erich.triumf.ca!bennett
  2. From: bennett@erich.triumf.ca (P.Bennett)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: scanf/gets interaction ?
  5. Date: 25 Mar 1996 10:10 PST
  6. Organization: TRIUMF: Tri-University Meson Facility
  7. Distribution: world
  8. Message-ID: <25MAR199610104015@erich.triumf.ca>
  9. References: <4j6joa$6ve@muller.loria.fr>
  10. NNTP-Posting-Host: ftp.triumf.ca
  11. News-Software: VAX/VMS VNEWS 1.50    
  12.  
  13. In article <4j6joa$6ve@muller.loria.fr>, roegel@loria.fr (Denis B. Roegel) writes...
  14. >I have the following program:
  15. >#include <stdio.h>
  16. >main(){
  17. >int n;
  18. >char num[10];
  19. >char*r;
  20. >fflush(stdin);
  21.  
  22. fflush() is undefined on input streams.
  23.  
  24. >printf("n: ");scanf("%i",&n);
  25. >printf("Numero ? ");r = gets(num);
  26. >printf("Bien recu!\n");
  27. >}
  28. >which I compile with gcc on SunOS. The program asks for a first number n which
  29. >I enter. But I never get a chance of entering a second one. Why is this so ?
  30.  
  31. scanf() leaves the '\n' in the input buffer, which gets() sees as the next
  32. entry.  Don't mix scanf() and gets() calls!  (In fact _don't_ use gets() at all
  33. - use fgets() instead - butt you still have the same problem...)
  34.  
  35. scanf() is very bad for direct user input - if it's looking for a number, and
  36. the user enters a letter, scanf() leaves the letter in the input stream, and
  37. you can never recover...
  38.  
  39. A better way to handle input is to use fgets() to get a line into a buffer,
  40. then you can check for valid input, and use sscanf() or other functions to
  41. convert the input as needed.
  42.  
  43. Peter Bennett VE7CEI                | Vessels shall be deemed to be in sight
  44. Internet: bennett@triumf.ca         | of one another only when one can be
  45. Packet: ve7cei@ve7kit.#vanc.bc.ca   | observed visually from the other
  46. TRIUMF, Vancouver, B.C., Canada     |                          ColRegs 3(k)
  47. GPS and NMEA info and programs: ftp://sundae.triumf.ca/pub/peter/index.html
  48. or: ftp://ftp-i2.informatik.rwth-aachen.de/pub/arnd/GPS/peter/index.html
  49.  
  50.